# -*- coding: utf-8 -*-
# @Time : 2021/02/23
# @Author : ricky
# @File : upgradespider.py
# @Software: vscode
"""
爬取gitee，检测更新
"""
import threading
import requests
import wx
from bs4 import BeautifulSoup
from constant import constant
from loguru import logger


class UpgradeThread(threading.Thread):
    def __init__(self, parent, show_no_new_version_tip=False):
        """
        :param parent:  主线程UI
        """
        super(UpgradeThread, self).__init__()
        self.parent = parent
        self.show_no_new_version_tip = show_no_new_version_tip
        self.setDaemon(True)

    def run(self):
        url = 'https://gitee.com/lpf_project/RuoYi-MT/releases'
        try:
            wb_data = requests.get(url)
            soup = BeautifulSoup(wb_data.text, 'html.parser')
            tags = soup.select('div .release-tag-item .release-meta .tag-name')
            if len(tags) == 0:
                return
            content = soup.select(
                'div .release-tag-item .release-body .content .markdown-body p')[0].text
            version_str = tags[0]['data-tag-name']
            version = ''.join(list(filter(str.isdigit, version_str)))
            if int(version) > constant.APP_VERSION_INT:
                wx.CallAfter(self.parent.upgrade_call_after, True, self.show_no_new_version_tip,
                             '新版本：%s\n\n更新日志：\n%s' % (version_str, content))
            else:
                wx.CallAfter(self.parent.upgrade_call_after,
                             False, self.show_no_new_version_tip, '当前版本是最新版本!')
        except Exception as error:
            logger.error('检查更新异常：%s' % error)
            wx.CallAfter(self.parent.upgrade_call_after,
                         False, self.show_no_new_version_tip, '检查更新失败，请检查网络连接是否正常')
